# -*- coding: utf-8 -*-

'''
Created on 18.11.2011

@author: vlasovai
'''

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User

from util import get_yandex_inflections

class UserProfile(models.Model):
    user = models.OneToOneField(User, editable=False)
    
    nominative = models.CharField(u'Именительный падеж', max_length=50)
    genitive = models.CharField(u'Родительный падеж', max_length=50)
    dative = models.CharField(u'Дательный падеж', max_length=50)
    accusative = models.CharField(u'Винительный падеж', max_length=50)
    ablative = models.CharField(u'Творительный падеж', max_length=50)
    prepositional = models.CharField(u'Предложный падеж', max_length=50)
    
    def __unicode__(self):
        return u'Профайл %s' % self.genitive

def create_user_profile(sender, instance, created, **kwargs):
    if created: #Создаем новую запись
            fio = u'%s %s'%(instance.last_name, instance.first_name)
            inflect_list = get_yandex_inflections(fio)
            if inflect_list and inflect_list.has_key('2'):
                profile = UserProfile(
                    user = instance,
                    nominative = inflect_list['1'],
                    genitive = inflect_list['2'],
                    dative = inflect_list['3'],
                    accusative = inflect_list['4'],
                    ablative = inflect_list['5'],
                    prepositional = inflect_list['6'],
                )
            #else: #Сохраняем только именительный падеж
            #    profile.nominative = fio
            #raise Exception(type(inflect_list['1']))
        
                profile.save(force_insert=True)
    else:#Проверяем и обновляем существующую
        # TODO: разобраться с изменением полей, узнать почему tuple пишется в базу вместо unicode
        try:
            profile = UserProfile.objects.get(user=instance)
            if not profile.genitive:
                fio = u'%s %s'%(instance.last_name, instance.first_name)
                inflect_list = get_yandex_inflections(fio)
                if inflect_list and inflect_list.has_key('2'):
                    profile.nominative = inflect_list['1'],
                    profile.genitive = inflect_list['2'],
                    profile.dative = inflect_list['3'],
                    profile.accusative = inflect_list['4'],
                    profile.ablative = inflect_list['5'],
                    profile.prepositional = inflect_list['6'],
                    
                    profile.save(force_update=True)
        except UserProfile.DoesNotExist:
            create_user_profile(sender, instance, created=True)
            
post_save.connect(create_user_profile, sender=User)

#def delete_user_profile(sender, instance, deleted, **kwargs):